<template>
  <div>
    <div class="card" style="margin-bottom: 5px;">
      <el-input style="width:240px; margin-right:10px" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button type="warning" @click="reset">重 置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px;">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger"  @click="delBatch">批量删除</el-button>
<!--      <el-button type="info">导 入</el-button>-->
<!--      <el-button type="success">导 出</el-button>-->
    </div>

    <div class="card" style="margin-bottom: 5px;">
      <el-table max-height="480" :data="data.tableData" stripe @selection-change="handleSelectionChange" style="width:100%">
        <el-table-column type="selection" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" />
        <el-table-column prop="no" label="工号" />
        <el-table-column prop="age" label="年龄"/>
        <el-table-column prop="description" label="个人介绍" show-overflow-tooltip/>
        <el-table-column prop="departmentName" label="部门" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="handleUpdate(scope.row)" type="info" :icon="Edit" circle  size="mini" />
            <el-button @click="del(scope.row.id)" type="danger" :icon="Delete" circle size="mini" />
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <el-dialog title="新增员工" v-model="data.formVisible"  width="500">
      <el-form :model="data.form" label-width="80px" style="padding-right:40px; padding-top: 20px">
        <el-form-item label="姓名" >
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="性别" >
          <el-radio-group v-model="data.form.sex">
            <el-radio value="男" label="男" />
            <el-radio value="女" label="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号" >
          <el-input v-model="data.form.no" autocomplete="off" placeholder="请输入工号"/>
        </el-form-item>
        <el-form-item label="年龄" >
          <el-input-number style="width:180px" :min="18" :max="55" v-model="data.form.age" autocomplete="off" placeholder="请输入年龄"/>
        </el-form-item>
        <el-form-item label="个人介绍" >
          <el-input type="textarea" v-model="data.form.description" autocomplete="off" rows="5" placeholder="简单的介绍一下自己吧~"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive } from 'vue'
import {Delete, Edit, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  name:null,
  tableData:[],
  pageNum:1,
  pageSize:10,
  total:0,
  formVisible:false,
  form:{},
  ids: []
})

// 定义数据加载函数
const load = () => {
  // 发起GET请求到分页查询接口
  request.get('/employee/selectPage', {   // 接口地址
    params: {  // 配置请求参数（最终会生成类似：/employee/selectPage?pageNum=1&pageSize=10&name=xxx的请求）
      pageNum: data.pageNum,    // 当前页码（来自响应式数据）
      pageSize: data.pageSize,  // 每页条数（来自响应式数据）
      name: data.name           // 查询条件（来自搜索框输入）
    }
  }).then(res => {  // 请求成功后的回调
    data.tableData = res.data.list  // 更新表格数据（使用接口返回的数据列表）
    data.total = res.data.total     // 更新总条数（用于分页器显示）
  })
}

load()

const reset = () => {
  data.name = null
  load()
}

const add =() =>{
  request.post('/employee/add', data.form).then(res => {     //新增的对象没有ID
    if(res.code === '200'){
      data.formVisible = false
      ElMessage.success('操作成功')
      load()  //新增后一定要重新加载最新的数据
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleAdd =() =>{
  data.formVisible = true
  data.form = {}
}

const update =() =>{
  request.put('/employee/updateById', data.form).then(res => {    //编辑的对象里面包含ID
    if(res.code === '200'){
      data.formVisible = false
      ElMessage.success('操作成功')
      load()      //更新后一定要重新加载最新的数据
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleUpdate = (row) =>{
  data.formVisible = true
  data.form = JSON.parse(JSON.stringify(row))     //深拷贝一个新的对象用于编辑，这样就不会影响行对象
}

/**
 * 删除指定ID的员工数据
 * @param {string|number} id - 要删除的员工记录的唯一标识符
 * @returns {void} 无直接返回值，通过副作用执行删除操作和状态更新
 */
const del = (id) =>{
  // 弹出确认对话框防止误操作
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？','删除确认', {type: 'warning'}).then(()=>{
    // 发送删除请求到后端接口
    request.delete('/employee/deleteById/' + id).then(res => {
      if(res.code === '200'){
        // 成功处理：关闭表单、显示通知、刷新数据
        data.formVisible = false
        ElMessage.success('操作成功')
        load()
      } else {
        // 处理业务逻辑错误
        ElMessage.error(res.msg)
      }
    })
  }).catch() // 用户取消删除时的静默处理
}

/**
 * 批量删除员工数据
 */
const delBatch = () => {
  request.delete('/employee/deleteBatch', {data : data.ids}).then(res => {
    if (data.ids.length === 0){
      ElMessage.warning('请选择数据')
      return
    }
    ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？','删除确认', {type: 'warning'}).then(() => {
      if(res.code === '200'){
        data.formVisible = false
        ElMessage.success('操作成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch()
  })
}



const save = () =>{  //在一个保存方法里面做两种操作  一个是新增，一个是编辑
  data.form.id ? update() : add()
}

const handleSelectionChange = (rows) =>{   //返回所有选中的行对象数组
  data.ids = rows.map(row => row.id)
}
</script>